package example;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by echo12 on 16/9/12.
 */


public class HttpClientAPI {

	public String HttpClientPostQequest(String smsUrl, JSONObject jsonObject) throws UnsupportedEncodingException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String URI = smsUrl;
		HttpPost httppost = new HttpPost(URI);
		String result = "";
		BufferedReader in = null;
		ByteArrayEntity arrayEntity = null;
		byte[] jsonBytes = null;
		if (jsonObject != null) {
			jsonBytes = jsonObject.toString().getBytes("UTF-8");
			arrayEntity = new ByteArrayEntity(jsonBytes);
		}
		try {
			httppost.addHeader("Content-Type", "application/json");
			httppost.addHeader("Accept", "application/json");
			if (arrayEntity != null) {
				arrayEntity.setContentEncoding("UTF-8");
				httppost.setEntity(arrayEntity);
			}

			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				in = new BufferedReader(new InputStreamReader(entity.getContent()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				EntityUtils.consume(entity);
			} finally {
				if (in != null) {
					in.close();
				}
				response.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			httppost.releaseConnection();
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String httpPost(String url, Map<String, String> params) {
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String result = "";
		BufferedReader in = null;
		try {
			// 创建httpget.
			HttpPost httpget = new HttpPost(url + "?" + paramConvert(params));
			System.out.println("executing request " + httpget.getURI());
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();
				in = new BufferedReader(new InputStreamReader(entity.getContent()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				EntityUtils.consume(entity);
			} finally {
				if (in != null) {
					in.close();
				}
				response.close();

			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String httpGet(String url, Map<String, String> params) {
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String result = "";
		BufferedReader in = null;
		try {
			// 创建httpget.
			HttpGet httpget = new HttpGet(url + "?" + paramConvert(params));
			System.out.println("executing request " + httpget.getURI());
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();
				in = new BufferedReader(new InputStreamReader(entity.getContent()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				EntityUtils.consume(entity);
			} finally {
				if (in != null) {
					in.close();
				}
				response.close();

			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	private static String paramConvert(Map<String, String> params) throws UnsupportedEncodingException {
		StringBuilder ps = new StringBuilder();
		if (params == null || params.size() < 1) {
			return "";
		}
		for (Map.Entry<String, String> p : params.entrySet()) {
			ps.append(p.getKey()).append("=").append(URLEncoder.encode(p.getValue(), "utf-8")).append("&");
		}
		return ps.deleteCharAt(ps.length() - 1).toString();
	}

	public static void main(String[] args) {
		String url = "https://www.baidu.com/s";
		Map<String, String> parammap = new HashMap<String, String>();
		String likeStr = "易源";
		parammap.put("wd", likeStr);
		String ret = httpGet(url, parammap);
		System.out.printf(ret);

	}

}
